<template>
	<div class="cart-page">
		<!-- 商品列表 -->
		<div class="product-list">
			<div class="product-item" v-for="(item, index) in cartItems" :key="index">
				<!-- 选中状态 -->
				<div class="select-section">
					<div class="select-btn" @click="toggleSelect(index)">
						<img v-if="item.gender" src="https://shalong.taiyanyue.top/images/fa5-check-circle-fas1.png" class="selected-icon" />
						<img v-else src="https://shalong.taiyanyue.top/images/weixuanz.png" class="unselected-icon" />
					</div>
					<div>
						<img class="product-image-placeholder" :src="item.goods_cover_path" alt="" />
					</div>
				</div>

				<!-- 商品信息 -->
				<div class="product-info">
					<div class="product-name-row">
						<div class="product-name">{{ item.goods_name }}</div>
						<!-- 删除按钮 -->
						<img src="https://shalong.taiyanyue.top/images/riFill-delete-bin-6-fill1.png" class="delete-btn"
							@click="confirmRemoveItem(item, index)" />
					</div>
					<div class="product-price-row">
						<div class="product-price" style="margin-right: 5px;">¥{{ item.goods_price }}</div>
						<div class="quantity-control">
							<span class="quantity-btn decrease-btn"
								@click="confirmDecreaseQuantity(item,index)">—</span>
							<input class="goods_quantity-input" type="number" min="1" v-model="item.goods_quantity"
								@change="updateQuantity(item)" @blur="validateQuantity(item)" />
							<span class="quantity-btn increase-btn" @click="increaseQuantity(item,index)">+</span>
						</div>
					</div>
				</div>
			</div>

			<!-- 加载更多提示 -->
			<view class="load-more" v-if="loading">
				<view class="loading-icon"></view>
				<text>{{loadText}}</text>
			</view>
			<view class="no-more" v-if="noMore && cartItems.length > 0">没有更多数据了</view>
			<view class="no-more" v-if="cartItems.length === 0">
				<div class="empty-text">购物车空空如也~</div>
			</view>
		</div>

		<div class="spacer"></div>

		<!-- 底部结算栏 -->
		<div class="checkout-bar">
			<!-- 全选按钮 -->
			<div class="select-all-row" @click="toggleSelectAll">
				<img v-if="allSelected" src="https://shalong.taiyanyue.top/images/fa5-check-circle-fas1.png" class="selected-icon" />
				<img v-else src="https://shalong.taiyanyue.top/images/weixuanz.png" class="unselected-icon" />
				<text class="select-all-text">全选</text>
			</div>

			<div class="divider"></div>

			<!-- 合计信息 -->
			<div class="total-row">
				<div class="total-label">商品合计</div>
				<div class="total-price">¥{{ totalPrice }}</div>
			</div>

			<!-- 结算按钮 -->
			<div class="action-buttons">
				<button class="checkout-btns" @click="confirmClearCart">
					<img class="trash-icon" src="https://shalong.taiyanyue.top/images/riFill-delete-bin-6-fill1.png" />
					<text class="checkout-btns-text">清空</text>
				</button>
				<button class="checkout-btn" @click="checkout">结算</button>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		goods_getShoppingCartList,
		goods_goodsShoppingCartInfoDelete,
		goods_clearShoppingCart,
		goods_goodsShoppingCartInfoSave,
		order_confirmGoodsOrderInfo
	} from '@/api/system/user.js'
	export default {
		data() {
			return {
				cartItems: [],
				currentPage: 1,
				pageSize: 5,
				totalItems: 0,
				loading: false,
				noMore: false,
				canLoad: true,
				isFirstLoad: true,
				updateTimer: null // 用于防抖的定时器
			}
		},
		computed: {
			totalPrice() {
				return this.cartItems.reduce((total, item) => {
					return item.gender ? total + item.goods_price * item.goods_quantity : total
				}, 0).toFixed(2)
			},
			allSelected() {
				return this.cartItems.every(item => item.gender)
			},
			loadText() {
				return this.loading ? '加载中...' : '上拉加载更多';
			}
		},
		created() {
			this.loadCartItems();
		},
		onReachBottom() {
			// 滚动到底部加载更多
			if (!this.noMore && this.canLoad && !this.isFirstLoad) {
				this.loadMore();
			}
		},
		methods: {
			async loadCartItems() {
				if (!this.canLoad) return;
				this.loading = true;
				this.canLoad = false;

				try {
					const data = await goods_getShoppingCartList({
						page: this.currentPage,
						size: this.pageSize
					});

					const newItems = data.content.data.map(item => ({
						...item,
						gender: false
					}));

					// 如果是第一页，直接赋值
					if (this.currentPage === 1 || this.isFirstLoad) {
						this.cartItems = newItems;
						this.isFirstLoad = false;
					} else {
						// 否则合并数据
						this.cartItems = [...this.cartItems, ...newItems];
					}

					this.totalItems = data.content.count || 0;

					// 判断是否还有更多数据
					if (this.cartItems.length >= this.totalItems || newItems.length < this.pageSize) {
						this.noMore = true;
					} else {
						this.noMore = false;
					}

					// 允许下次加载
					this.canLoad = true;
				} catch (error) {
					console.error('加载购物车数据失败:', error);
					this.canLoad = true;
				} finally {
					this.loading = false;
				}
			},

			// 加载更多
			loadMore() {
				if (this.noMore || !this.canLoad) return;

				this.currentPage += 1;
				this.loadCartItems();
			},

			confirmRemoveItem(item, index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除此商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.removeItem(item, index);
						}
					}
				});
			},

			confirmDecreaseQuantity(item, index) {
				if (this.cartItems[index].goods_quantity === 1) {
					uni.showModal({
						title: '提示',
						content: '确定要删除此商品吗？',
						success: (res) => {
							if (res.confirm) {
								const item = this.cartItems[index];
								this.removeItem(item, index);
							}
						}
					});
				} else {
					this.decreaseQuantity(item, index);
				}
			},

			confirmClearCart() {
				uni.showModal({
					title: '提示',
					content: '确定要清空购物车吗？',
					success: (res) => {
						if (res.confirm) {
							this.qingk();
						}
					}
				});
			},

			async qingk() {
				const data = await goods_clearShoppingCart();
				if (data.code == 200) {
					uni.showToast({
						title: '清空成功',
						icon: 'none',
						duration: 1500
					});
					this.cartItems = [];
					this.noMore = false;
					this.currentPage = 1;
					this.isFirstLoad = true;
				} else {
					uni.showToast({
						title: '清空失败',
						icon: 'none',
						duration: 1500
					});
				}
			},

			toggleSelect(index) {
				this.cartItems[index].gender = !this.cartItems[index].gender
			},

			toggleSelectAll() {
				const selectAll = !this.allSelected
				this.cartItems.forEach(item => {
					item.gender = selectAll
				})
			},

			// 更新数量（输入框变化时调用）
			async updateQuantity(item) {
				console.log(item, 123)
				// 防抖处理，避免快速输入时频繁请求
				if (this.updateTimer) {
					clearTimeout(this.updateTimer);
				}

				this.updateTimer = setTimeout(async () => {
					try {
						// 确保数量至少为1
						const quantity = Math.max(1, parseInt(item.goods_quantity) || 1);
						console.log(123)
						// 如果数量没有变化，不发起请求
						if (quantity === item.goods_quantity) return;
						console.log(13)
						const res = await goods_goodsShoppingCartInfoSave({
							goods_id: item.goods_id,
							goods_quantity: item.goods_quantity, // 传递差值
							is_check: 0
						});

						if (res.code == 200) {
							// 更新本地数据
							item.goods_quantity = quantity;
						} else {
							// 恢复原始值
							item.goods_quantity = item.goods_quantity;
							uni.showToast({
								title: '更新数量失败',
								icon: 'none',
								duration: 1500
							});
						}
					} catch (error) {
						console.error('更新数量失败:', error);
						// 恢复原始值
						item.goods_quantity = item.goods_quantity;
						uni.showToast({
							title: '更新数量失败',
							icon: 'none',
							duration: 1500
						});
					} finally {
						this.updateTimer = null;
					}
				}, 500); // 500ms防抖延迟
			},

			// 验证输入数量
			validateQuantity(item) {
				// 确保数量是正整数
				const quantity = parseInt(item.goods_quantity);
				if (isNaN(quantity) || quantity < 1) {
					item.goods_quantity = 1;
					uni.showToast({
						title: '数量必须大于0',
						icon: 'none',
						duration: 1500
					});
				}
			},

			increaseQuantity(item, index) {
				goods_goodsShoppingCartInfoSave({
					goods_id: item.goods_id,
					goods_quantity: 1,
					is_check: 1
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '购物车数量加一',
							icon: 'none',
							duration: 1500
						});
						// 更新购物车数量
						this.cartItems[index].goods_quantity++
					} else {
						uni.showToast({
							title: '加入购物车失败',
							icon: 'none',
							duration: 1500
						});
					}
				})
			},

			decreaseQuantity(item, index) {
				if (this.cartItems[index].goods_quantity > 1) {
					goods_goodsShoppingCartInfoSave({
						goods_id: item.goods_id,
						goods_quantity: -1,
						is_check: 1
					}).then(res => {
						if (res.code == 200) {
							uni.showToast({
								title: '购物车数量减一',
								icon: 'none',
								duration: 1500
							});
							// 更新购物车数量
							this.cartItems[index].goods_quantity--
						} else {
							uni.showToast({
								title: '加入购物车失败',
								icon: 'none',
								duration: 1500
							});
						}
					})
				}
			},

			async removeItem(item, index) {
				const data = await goods_goodsShoppingCartInfoDelete({
					goods_id: item.goods_id
				});
				if (data.code == 200) {
					this.cartItems.splice(index, 1);
					uni.showToast({
						title: '删除成功',
						icon: 'none',
						duration: 1500
					});
					// 如果当前页没有数据了，返回上一页
					if (this.cartItems.length === 0 && this.currentPage > 1) {
						this.currentPage--;
					}
					this.loadCartItems();
				}
			},

			async checkout() {
				// 检查是否有选中的商品
				  const hasSelectedItems = this.cartItems.some(item => item.gender);
				  
				  if (!hasSelectedItems) {
				    uni.showToast({
				      title: '您还没有选择宝贝哦~',
				      icon: 'none',
				      duration: 1500
				    });
				    return; // 终止后续逻辑
				  }
				let a = []
				for (let i = 0; i < this.cartItems.length; i++) {
					if (this.cartItems[i].gender) {
						a.push({
							goods_id: this.cartItems[i].goods_id,
							purchase_quantity: this.cartItems[i].goods_quantity
						})
					}
				}
				const data = await order_confirmGoodsOrderInfo({goods_arr:a})
				if(data.code==200){
					let c={
						order_sn:'',
						data:data.content.data
					}
					const params = encodeURIComponent(JSON.stringify(c));
					  uni.navigateTo({
					    url: `/pages/orderConfirmation?data=${params}`
					  });
				} 
			}
		}
	}
</script>

<style scoped>
	/* 原有样式保持不变，只添加输入框相关样式 */

	.goods_quantity-input {
		width: 40px;
		height: 24px;
		text-align: center;
		border: 1px solid #efefef;
		border-radius: 4px;
		margin: 0 5px;
	}

	/* 移除数字输入框的上下箭头（适用于WebKit浏览器） */
	.goods_quantity-input::-webkit-outer-spin-button,
	.goods_quantity-input::-webkit-inner-spin-button {
		-webkit-appearance: none;
		margin: 0;
	}

	/* Firefox */
	.goods_quantity-input[type=number] {
		-moz-appearance: textfield;
	}

	/* 其他原有样式保持不变 */
	.cart-page {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.product-list {
		padding: 12px;
	}

	.product-item {
		display: flex;
		background: #fff;
		padding: 16px;
		margin-bottom: 12px;
		border-radius: 8px;
	}

	.select-section {
		display: flex;
		align-items: center;
		margin-right: 12px;
	}

	.select-btn {
		margin-right: 12px;
	}

	.selected-icon,
	.unselected-icon {
		width: 22px;
		height: 22px;
	}

	.product-image-placeholder {
		width: 100px;
		height: 100px;
		border-radius: 12px;
	}

	.product-info {
		flex: 1;
	}

	.product-name-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 15px;
	}

	.product-name {
		font-size: 16px;
		color: #333;
		font-weight: 550;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
		max-height: 48px;
		line-height: 24px;
	}

	.delete-btn {
		width: 80px;
		height: 20px;
	}

	.product-price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 25px;
	}

	.product-price {
		font-size: 16px;
		font-weight: 550;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		background: #efefef;
		border-radius: 12px;
		color: #339966;
		width: 90px;
	}

	.quantity-btn {
		width: 32px;
		height: 32px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.decrease-btn {
		font-size: 16px;
	}

	.increase-btn {
		font-size: 22px;
	}

	.spacer {
		width: 100%;
		height: 180px;
	}

	.checkout-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 12px 16px;
		background: #ffffff;
		border-top: 1px solid #f0f0f0;
		border-radius: 35px 35px 0 0;
	}

	.select-all-row {
		display: flex;
		align-items: center;
		padding-top: 15px;
		margin-bottom: 15px;
	}

	.select-all-text {
		margin-left: 10px;
		font-size: 16px;
		color: #8a8a8a;
	}

	.divider {
		height: 1px;
		width: 100%;
		background: #f1f1f1;
	}

	.total-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 15px 0;
	}

	.total-label {
		font-size: 17px;
	}

	.total-price {
		font-size: 20px;
		font-weight: 550;
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.checkout-btns {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 50%;
		border: 1px solid #339966;
		border-radius: 20px;
		font-size: 16px;
		color: #339966;
		padding: 8px 0 8px 0;
		background: transparent;
		margin-right: 15px;
	}

	.trash-icon {
		width: 20px;
		height: 20px;
		margin-right: 5px;
	}

	.checkout-btns-text {
		line-height: 1.5;
	}

	.checkout-btn {
		width: 100%;
		background: #339966;
		color: #fff;
		border: none;
		border-radius: 20px;
		font-size: 16px;
		padding: 2px 0;
	}

	/* 分页样式 */
	.pagination {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 15px 0;
		background-color: #fff;
		margin: 10px 0;
	}

	.page-btn {
		margin: 0 10px;
		padding: 5px 10px;
		border: 1px solid #ddd;
		background-color: #f9f9f9;
		border-radius: 4px;
		min-width: 60px;
	}

	.page-btn[disabled] {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.page-info {
		margin: 0 10px;
		font-size: 14px;
		color: #666;
	}

	/* 加载动画 */
	.loading-icon {
		width: 16px;
		height: 16px;
		border: 2px solid #eee;
		border-top: 2px solid #5cab84;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-right: 8px;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	/* 加载更多提示 */
	.load-more,
	.no-more {
		width: 100%;
		text-align: center;
		padding: 10px 0;
		color: #999;
		font-size: 14px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.no-more {
		color: #ccc;
	}
</style>